<template>
  <div class="components-myupload">
      <ul class="el-upload-list el-upload-list--picture-card" v-if="isShowList && listType == 'picture-card' && file_list.length > 0">
          <li v-for="(item,index) in file_list" :key="index" tabindex="0" class="el-upload-list__item is-ready">
              <div>
                  <video width="120" height="120" controls v-if="fileMedia == 'video'"  class="el-upload-list__item-thumbnail">
                      <source :src="getUrl(item.url)" type="video/mp4">
                  </video>
                  <img v-else :src="getUrl(item.url)" alt="" class="el-upload-list__item-thumbnail">
                  <!-- <img :src="getUrl(item)" alt="" class="el-upload-list__item-thumbnail">  -->
                  <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(item)"><el-icon><ZoomIn /></el-icon></span>
                      <span class="el-upload-list__item-delete" @click="uploadRemove(index)"><el-icon><Delete /></el-icon></span>
                  </span>
              </div>
          </li>
      </ul>
      <el-upload
          :class="'upload-'+listType"
          ref="refUploadFile"
          :action="uploadFileUrl"
          :headers="headers"
          :list-type="listType"      
          :limit="limit"
          :multiple="limit>1 ? true : false"
          :accept="acceptType"
          :on-error="uploadError"
          :on-progress="uploadProgress"
          :before-upload="handleBeforeUpload"
          :on-success="uploadSuccess"
          :show-file-list="false"
          :data="uploadData"
          :name="fileName">
          <!-- :on-exceed="handleExceed" -->
          <!-- <i v-if="listType == 'picture-card'" class="el-icon-plus" v-loading="loading"></i> -->
          <el-icon v-if="listType == 'picture-card'" v-loading="loading" class="avatar-uploader-icon"><Plus /></el-icon>
          <el-button v-else size="small" icon="el-icon-upload2" type="primary" plain :loading="loading">点击上传</el-button>     
      </el-upload>
      <div class="el-upload__tip" slot="tip" v-if="showTip">
          请上传
          <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
          <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
          的文件
      </div>
      <ul class="el-upload-list el-upload-list--text" v-if="isShowList && listType == 'text' && file_list.length > 0">
          <li tabindex="0" class="el-upload-list__item is-success"  v-for="(item,index) in file_list" :key="index">
              <a class="el-upload-list__item-name">
                  <i class="el-icon-document"></i>{{item.name}}
              </a>
              <label class="el-upload-list__item-status-label">
                  <i class="el-icon-upload-success el-icon-circle-check"></i>
              </label>
              <i class="el-icon-close" @click="uploadRemove(index)"></i>
              <i class="el-icon-close-tip">按 delete 键可删除</i>
          </li>
      </ul>
  <el-dialog :visible.sync="dlg_view.is_show" append-to-body>
      <div class="align-center">
          <video width="200" height="200" controls v-if="fileMedia == 'video'">
              <source :src="getUrl(dlg_view.url)" type="video/mp4">
          </video>
          <img v-else style="max-width:100%" :src="getUrl(dlg_view.url)" alt="">
      </div>
  </el-dialog>
  </div>    
</template>
<script setup lang="ts">
import { ComponentInternalInstance } from "vue";
import { Session } from '/@/utils/storage';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(['update:modelValue', 'success']);
const props = defineProps({
  modelValue: String,
  listType: {
      type : String,
      default: () => 'picture-card',
  },
  ileMedia: { // 上传文件的类型，主要是区分视频和图片
      type: String,
  },
  fileSize: {
      type: Number,
      default: 100,
  },
  fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg","doc", "docx", "xls", "xlsx", "ppt", "txt", "pdf", "rar", "zip", "7z"],
  },
  fileName:{
      type: String,
      default: () => 'file'
  },
  isShowTip: {
      type: Boolean,
      default: false
  },
  isShowList:{
      type: Boolean,
      default: true
  },
  params:{
      type: Object,
      default: () => { return {type: 1,} }
  },
  limit:{
      type: Number,
      default: () => 1
  },
  api: {
      type: String,
      default: () => '/config/file/upload',//'/admin/sys-file/upload',
  }
});
const refUploadFile = ref();
const loading = ref(false);
const baseUrl = import.meta.env.VITE_API_URL;
const uploadFileUrl = ref(baseUrl + props.api);
const uploadData = reactive({
    type:1,
    attachFileGroupId: '',
    shopId: 0,//localStorage.getItem('shopId'),
    file: null,
});
const headers = reactive({
  Authorization: 'Bearer ' + Session.getToken(),
  'TENANT-ID' : Session.getTenant(),
});
let file_list = reactive([]);
const file = ref();
const dlg_view = reactive({
              is_show: false,
              url: null,
          });

const acceptType = computed(() => {
  let arr = props.fileType.map(item => '.'+item);
  return arr.join(',');
});
// 是否显示提示
const showTip = computed(() => {
  return props.isShowTip && (props.fileType || props.fileSize);
});
// 列表
const list = computed(() => {
    console.log(props.modelValue);
  if (props.modelValue) {
      // 首先将值转为数组
      let list;
      if(Array.isArray(props.modelValue) ){
          list = props.modelValue;
      }else{
          list = props.modelValue.split(',');
      }
      // 然后将数组转为对象数组
      return list.map((item) => {
          if (typeof item === "string") {
              item = { name: item, url: item };
          }
          return item;
      });
  } else {
      file_list = [];
      // this.$forceUpdate();
      return [];
  }
});
// 上传前校检格式和大小
const handleBeforeUpload = (file) => {
  file.value = file;
   // 校检文件类型
  if (props.fileType) {
      let fileExtension = "";
      if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
      }
      const isTypeOk = props.fileType.some((type) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
      });
      if (!isTypeOk) {
      proxy.$message.error(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
      }
  }
  // 校检文件大小
  if (props.fileSize) {
      const isLt = file.size / 1024 / 1024 < props.fileSize;
      if (!isLt) {
          proxy.$message.error(`上传文件大小不能超过 ${props.fileSize} MB!`);
          return false;
      }
  }
  uploadData.file = file;
  return true;
};
const handleExceed = (files, fileList) => {
    console.log('hhh')
  proxy.$message.error(`上传的文件已超过` + props.limit + '个');
};
const uploadProgress = (event,file, fileList) => {
  loading.value = true;
};
const uploadSuccess = (res, file, fileList) => {
  loading.value = false;
  if(res.hasOwnProperty('code')){
      if (res.code == 0 || res.code == 200) {
          if(props.limit > 1){
              if(file_list.length < props.limit){
                  file_list.push({name: file.name , url: res.data.resourcesUrl+res.data.filePath, fileName:res.data.filePath, res: res.data});
              }else{
                  proxy.$message.error(`上传的文件已超过` + props.limit + '个');
              }
          }
          if(props.limit == 1){
              file_list.push({name: file.name , url: res.data.resourcesUrl+res.data.filePath, fileName:res.data.filePath, res: res.data});
          }
          let fileName = file_list.map(item => item.fileName);
          emit('update:modelValue', fileName.join(','))
          emit('success', file_list);
      } else {
          proxy.$message.error(res.msg)
      }
  }else{
      emit('success', res);
  }
  if(props.limit == 1){
      refUploadFile.value.clearFiles();
  }
};
const uploadRemove = (index) => {
  file_list.splice(index, 1);
  // this.$forceUpdate();
  let fileName = file_list.map(item => item.fileName);
  emit('update:modelValue', fileName.join(','));
  emit('success', file_list);
};
const uploadError = (err) => {
  loading.value = false;
  proxy.$message.error('上传失败，请重试')
};
// 预览
const handlePictureCardPreview = (file) => {
  dlg_view.url = file.url;
  dlg_view.is_show = true;
};
// 如果上传成功返回的url不是可访问的地址，则加上域名
const getUrl = (url) => {
  console.log(url);
  if(url){
      if(url.indexOf('http') == -1){
          // return fileUrl + url;
          return 'https://yjh-shop.oss-cn-beijing.aliyuncs.com/' + url;
      }else{
        return url;
      }
  }
  return 'https://yjh-shop.oss-cn-beijing.aliyuncs.com/' + url;
};
</script>
<style lang="scss" scoped>
.components-myupload{
.upload{
  &-picture-card{
    display:inline-block;
    :deep .el-upload--picture-card{
        width:108px;height:108px;line-height:106px;
    }
    
  }
}
.el-upload-list--picture-card{
     display:inline-block;height:108px;float:left;
     .el-upload-list__item{
        width:108px;height:108px;
     }
  }
}
</style>